﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
using MySql.Data.MySqlClient;

namespace BTComunnicator
{
    class Program
    {
        private static List<Device> devices = new List<Device>();
        private static BackgroundWorker bg;
        private static Guid service = new Guid("{7A51FDC2-FDDF-4c9b-AFFC-98BCD91BF93B}");
        private static SerialPort port;
        private static InTheHand.Net.Sockets.BluetoothDeviceInfo info;
        private static List<device> devicesFromDb = new List<device>();

        static MySqlConnection conn = ConnectionPool.checkOutConnection();
        static heartdb db;
        static void Main(string[] args)
        {
            initBGWorker();
            bg.RunWorkerAsync();
            db = new heartdb(conn);
            
            getDevicesFromDB();
            Console.WriteLine("Start scaning...");
            Console.Read();
        }

        static public void initBGWorker()
        {
            bg = new BackgroundWorker();
            bg.DoWork += new DoWorkEventHandler(bg_DoWork);
            bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
        }

        static void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine("Scaning done...");
            connectDevice(devices[0], "1234");
        }

        static void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient();
            InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
            int count = array.Length;
            for (int i = 0; i < count; i++)
            {
                Device device = new Device(array[i]);
                devices.Add(device);
                Console.WriteLine(device.DeviceName+" found");
            }
        }
        static void connectDevice(Device device, string pairPin)
        {
            InTheHand.Net.Bluetooth.BluetoothSecurity.PairRequest(device.Address, pairPin);
            info = new InTheHand.Net.Sockets.BluetoothDeviceInfo(device.Address);
            info.SetServiceState(InTheHand.Net.Bluetooth.BluetoothService.SerialPort, true);
            port = new SerialPort(SerialPort.GetPortNames().Last());
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
           
            if (!port.IsOpen)
            {
                port.Open();
            }
            Console.WriteLine("Device " + device.DeviceName + " is connected!");
        }

        static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            int readedChar= sp.ReadChar();
            Console.WriteLine("Received data: " + readedChar);
            insertValueInDb(1, Decimal.Parse(readedChar.ToString()));
        }

        static void getDevicesFromDB()
        {
            var query = from d in db.device where d.Status == "radi" select d;
            foreach (var q in query)
            {
                devicesFromDb.Add((device)q);
            }
        }

        static void insertValueInDb(uint deviceID, decimal value)
        {
            Console.WriteLine("Insert into database value: " + value);
            var idQuery = (from d in db.devicehaspatient where d.Deviceid == deviceID select new {deviceId = d.id }).First();
            uint id = idQuery.deviceId;
            latestactivity la = new latestactivity();
            la.OxigenLevel = value;
            la.BloodPresure = 110;
            la.HeartRate = 67;
            la.DevicehasPatientid = id;
            la.Updatedate = DateTime.Now;
            db.latestactivity.InsertOnSubmit(la);
            db.SubmitChanges();
        }
    }
}
